package org.huang;

import com.alibaba.fastjson.JSON;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.hyperledger.fabric.contract.Context;
import org.hyperledger.fabric.contract.ContractInterface;
import org.hyperledger.fabric.contract.annotation.*;
import org.hyperledger.fabric.shim.ChaincodeException;
import org.hyperledger.fabric.shim.ChaincodeStub;
import org.hyperledger.fabric.shim.ledger.KeyModification;
import org.hyperledger.fabric.shim.ledger.KeyValue;
import org.hyperledger.fabric.shim.ledger.QueryResultsIterator;

import javax.jws.Oneway;
import java.util.*;

@Contract(
        name = "OwnerContract",
        info = @Info(
                title = "Owner contract",
                description = "The hyperlegendary car contract",
                version = "0.0.1-SNAPSHOT",
                license = @License(
                        name = "Apache 2.0 License",
                        url = "http://www.apache.org/licenses/LICENSE-2.0.html"),
                contact = @Contact(
                        email = "f.carr@example.com",
                        name = "F Carr",
                        url = "https://hyperledger.example.com")))
@Log
public class OwnerContract implements ContractInterface {
    @Transaction
    public void initLedger(final Context ctx) {

        ChaincodeStub stub = ctx.getStub();
        for (int i = 0; i < 10; i++ ) {
            Owner owner=new Owner().setId("owner-"+i).setName("lisi");
            stub.putStringState(owner.getId() , JSON.toJSONString(owner));
        }

    }

    @Transaction
    public Owner queryOwner(final Context ctx, final String id) {

        ChaincodeStub stub = ctx.getStub();
        String catState = stub.getStringState(id);

        if (StringUtils.isBlank(catState)) {
            String errorMessage = String.format("Owner %s does not exist", id);
            System.out.println(errorMessage);
            throw new ChaincodeException(errorMessage);
        }

        return JSON.parseObject(catState , Owner.class);
    }

    @Transaction
    public Owner createOwner(final Context ctx, final String id , String name ) {

        ChaincodeStub stub = ctx.getStub();
        String catState = stub.getStringState(id);

        if (StringUtils.isNotBlank(catState)) {
            String errorMessage = String.format("Owner %s already exists", id);
            System.out.println(errorMessage);
            throw new ChaincodeException(errorMessage);
        }

        Owner owner=new Owner().setId(id).setName(name);


        String json = JSON.toJSONString(owner);
        stub.putStringState(id, json);

        stub.setEvent("createOwnerEvent" , org.apache.commons.codec.binary.StringUtils.getBytesUtf8(json));
        return owner;
    }

    @Transaction
    public Owner updateOwner(final Context ctx, final String id , String name , String GoodsName) {

        ChaincodeStub stub = ctx.getStub();
        String catState = stub.getStringState(id);

        if (StringUtils.isBlank(catState)) {
            String errorMessage = String.format("owner %s does not exist", id);
            System.out.println(errorMessage);
            throw new ChaincodeException(errorMessage);
        }

       Owner owner=new Owner().setId(id).setName(name).setName("lisi");


        stub.putStringState(id, JSON.toJSONString(owner));

        return owner;
    }

    @Transaction
    public Owner deleteOwner(final Context ctx, final String id) {

        ChaincodeStub stub = ctx.getStub();
        String catState = stub.getStringState(id);

        if (StringUtils.isBlank(catState)) {
            String errorMessage = String.format("owner %s does not exist",id);
            System.out.println(errorMessage);
            throw new ChaincodeException(errorMessage);
        }

        stub.delState(id);

        return JSON.parseObject(catState , Owner.class);
    }
    /**
     * 获取该key的所有变更记录
     */
    @Transaction(intent = Transaction.TYPE.EVALUATE)
    public String getHistoryFromKey(final Context ctx, final String id) {
        Map<String, String> userHistory = new HashMap<>();
        ChaincodeStub stub = ctx.getStub();
        QueryResultsIterator<KeyModification> iterator = stub.getHistoryForKey(id);
        for (KeyModification result: iterator) {
            userHistory.put(result.getTxId(), result.getStringValue());
        }
        return JSON.toJSONString(userHistory);
    }

    /**
     * 查询所有的合约
     */
    @Transaction(intent = Transaction.TYPE.EVALUATE)
    public String queryAll(final Context ctx) {
        ChaincodeStub stub = ctx.getStub();
        List<Owner> userList = new ArrayList<>();
        QueryResultsIterator<KeyValue> results = stub.getStateByRange("", "");
        for (KeyValue result: results) {
            Owner owner = JSON.parseObject(result.getStringValue(), Owner.class);
            System.out.println(owner);
            userList.add(owner);
        }
        return JSON.toJSONString(userList);
    }

    @Override
    public void afterTransaction(Context ctx, Object result) {

    }
}
